package ua.races.command.implementation;

import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Horse;
import ua.races.vo.HorseRace;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PostRaceCommand implements ServletCommand {
    private static final Logger log = Logger.getLogger(PostRaceCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        Race race = null;
        RacesDaoImpl dao;
        Horse horse = null;
        List<Horse> horses = null;
        String stadium;
        long raceId;

        String[] dbHorseNames = null;
        String[] resultValues = null;
        String redirectUrl = null;
        String message = null;

        try {
            message = "Sorry, you had inputted wrong data " +
                    "and race have not been successfully added (((";
            redirectUrl = req.getHeader("referer");
            dao = (RacesDaoImpl) context.getAttribute("DAO");

            dbHorseNames = req.getParameterValues("horse");
            for (int i = 0; i < dbHorseNames.length; i++) {
                if (dbHorseNames[i].matches("^.*-->.*$")) {
                    dbHorseNames[i] = req.getParameterValues("horseName")[i].trim();
                    horse = new Horse();
                    horse.setHorseName(dbHorseNames[i]);
                    checkHorseUnique(dao, horse);
                    dao.addNewHorse(horse);
                }
            }

            race = new Race();
            if (req.getParameter("stadium").matches("^.*-->.*$")) {
                stadium = req.getParameter("newStadium").trim();
            } else {
                stadium = req.getParameter("stadium").trim();
            }

            race.setStadium(stadium);
            race.setRaceDate(Date.valueOf(req.getParameter("date")));
            race.setStartTime(Time.valueOf(req.getParameter("time")));
            raceId = dao.addNewRace(race);

            horses = new ArrayList<Horse>();
            for (String horseName : dbHorseNames) {
                for (Horse h : dao.findAllHorses()) {
                    if (h.getHorseName().equalsIgnoreCase(horseName)) {
                        if (!horses.contains(h)) {
                            horses.add(h);
                        } else {
                            throw new SQLException("same horses in one race");
                        }
                    }
                }
            }

            if (dbHorseNames.length != dao.addNewHorseRace(raceId, horses)) {
                throw new SQLException("wrong input data");
            } else {
                message = "Your race has been successfully added";
                redirectUrl = "/prepareAdmin.do";
                log.info("Race has been successfully posted");
            }
        } catch (Throwable e) {
            log.error(e);
            try {
                resp.sendRedirect("/pipec.jsp");
            } catch (IOException e1) {
                log.fatal(e1);
            }
        } finally {
            try {
                req.setAttribute("message", message);
                req.setAttribute("URL", redirectUrl);
                context.getRequestDispatcher("/redirection.jsp").forward(req, resp);
            } catch (ServletException e) {
                log.error(e);
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

    protected void checkHorseUnique(RacesDaoImpl dao, Horse horse) throws SQLException {
        for (Horse h : dao.findAllHorses()) {
            if (h.getHorseName().equalsIgnoreCase(horse.getHorseName()) || (horse.getHorseName().matches("^\\s*$"))) {
                throw new SQLException("new horse has the same name with horse in db");
            }
        }
    }


}